package com.wifiKey.android.util.oaid

import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import androidx.core.app.ActivityCompat
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.lang.reflect.Method
import java.net.NetworkInterface
import java.util.Collections
import java.util.Locale

class StringIds {

    /**获取androidId*/
    fun getAndroidId(context: Context): String {
        return Settings.System.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
    }

    /**获取imei*/
    fun getImei(context: Context): String {
        val imei =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {// android 10
                ""
            } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) { // android 8 - 9
                val map: Map<String, String> = getIMEIforO(context)
                if (!TextUtils.isEmpty(map["imei1"])) {
                    map["imei1"] ?: ""
                } else {
                    map["imei2"] ?: ""
                }
            } else {
                val mapImei: Map<String, String> = getImeiAndMeid(context)
                if (!TextUtils.isEmpty(mapImei["meid"])) {
                    mapImei["meid"] ?: ""
                } else if (!TextUtils.isEmpty(mapImei["imei1"])) {
                    mapImei["imei1"] ?: ""
                } else {
                    mapImei["imei2"] ?: ""
                }
            }
        return imei
    }

    private fun getIMEIforO(context: Context): Map<String, String> {
        val map: MutableMap<String, String> =
            HashMap()
        val tm =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (ActivityCompat.checkSelfPermission(context,Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
            || tm == null) { // 没有权限
            Log.e("DeviceInfoUtil", "getIMEIforO: no permission")
            map["imei1"] = ""
            map["imei2"] = ""
            return map
        }
        val imei1 = tm.getImei(0)
        val imei2 = tm.getImei(1)
        if (TextUtils.isEmpty(imei1) && TextUtils.isEmpty(imei2)) {
            map["imei1"] = tm.meid //如果CDMA制式手机返回MEID
        } else {
            map["imei1"] = imei1 ?: ""
            map["imei2"] = imei2 ?: ""
        }
        return map
    }


    /**
     * 5.0统一使用这个获取IMEI IMEI2 MEID
     *
     * @param ctx
     * @return
     */
    @SuppressLint("MissingPermission")
    @TargetApi(Build.VERSION_CODES.M)
    private fun getImeiAndMeid(ctx: Context): Map<String, String> {
        val map: MutableMap<String, String> = HashMap()
        val mTelephonyManager = ctx.getSystemService(Activity.TELEPHONY_SERVICE) as TelephonyManager
        var clazz: Class<*>? = null
        var method: Method? = null //(int slotId)
        try {
            clazz = Class.forName("android.os.SystemProperties")
            method = clazz.getMethod("get", String::class.java, String::class.java)
            val gsm = method.invoke(null, "ril.gsm.imei", "") as String
            val meid = method.invoke(null, "ril.cdma.meid", "") as String
            map["meid"] = meid
            if (!TextUtils.isEmpty(gsm)) { //the value of gsm like:xxxxxx,xxxxxx
                val imeiArray = gsm.split(",").toTypedArray()
                if (imeiArray != null && imeiArray.size > 0) {
                    map["imei1"] = imeiArray[0]
                    if (imeiArray.size > 1) {
                        map["imei2"] = imeiArray[1]
                    } else {
                        map["imei2"] = mTelephonyManager.getDeviceId(1)
                    }
                } else {
                    map["imei1"] = mTelephonyManager.getDeviceId(0)
                    map["imei2"] = mTelephonyManager.getDeviceId(1)
                }
            } else {
                map["imei1"] = mTelephonyManager.getDeviceId(0)
                map["imei2"] = mTelephonyManager.getDeviceId(1)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return map
    }

    /**获取mac地址*/
    fun getMacFromHardware(context: Context): String {
        var macAddress = ""
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { //5.0以下
                macAddress = getMacDefault(context) ?: ""
                if (macAddress != null) {
                    if (!macAddress.equals("020000000000", ignoreCase = true)) {
                        return macAddress
                    }
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                macAddress = getMacAddress() ?: ""
                if (macAddress != null) {
                    if (!macAddress.equals("020000000000", ignoreCase = true)) {
                        return macAddress.uppercase()
                    }
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                macAddress = getMacFromWlan() ?: ""
                if (macAddress != null) {
                    if (!macAddress.equals("020000000000", ignoreCase = true)) {
                        return macAddress.uppercase()
                    }
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return macAddress.uppercase()
    }

    /**
     * Android  6.0 之前（不包括6.0）
     * 必须的权限  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    private fun getMacDefault(context: Context?): String? {
        var mac: String? = null
        if (context == null) {
            return mac
        }
        val wifi = context.applicationContext
            .getSystemService(Context.WIFI_SERVICE) as WifiManager
        var info: WifiInfo? = null
        try {
            info = wifi.connectionInfo
        } catch (e: Exception) {
        }
        if (info == null) {
            return null
        }
        mac = info.macAddress
        if (!TextUtils.isEmpty(mac)) {
            mac = mac.toUpperCase(Locale.ENGLISH)
        }
        return mac
    }

    /**
     * Android 6.0（包括） - Android 7.0（不包括）
     * @return
     */
    private fun getMacAddress(): String? {
        var WifiAddress: String? = null
        try {
            WifiAddress =
                BufferedReader(FileReader(File("/sys/class/net/wlan0/address")))
                    .readLine()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return WifiAddress
    }

    /**
     * 遍历循环所有的网络接口，找到接口是 wlan0
     * 必须的权限 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     * @return
     */
    private fun getMacFromWlan(): String? {
        try {
            val all: List<NetworkInterface> =
                Collections.list(NetworkInterface.getNetworkInterfaces())
            Log.d("Utils", "all:" + all.size)
            for (nif in all) {
                if (!nif.name.equals("wlan0", ignoreCase = true)) continue
                val macBytes = nif.hardwareAddress ?: return null
                Log.d("Utils", "macBytes:" + macBytes.size + "," + nif.name)
                val res1 = StringBuilder()
                for (b in macBytes) {
                    res1.append(String.format("%02X:", b))
                }
                if (res1.isNotEmpty()) {
                    res1.deleteCharAt(res1.length - 1)
                }
                return res1.toString()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}